package com.now.printer.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.now.printer.R;
import com.now.printer.base.BaseActivity2;
import com.now.printer.base.x5.FileReaderView;
import com.now.printer.db.RecentlyTable;
import com.now.printer.http.Xutils;
import com.now.printer.idcardcamera.camera.CameraActivity;
import com.now.printer.idcardcamera.cropper.CropImageView;
import com.now.printer.idcardcamera.cropper.CropListener;
import com.now.printer.print.PDFCheck;
import com.now.printer.utils.ConvertUtils;
import com.now.printer.utils.DbUtils;
import com.now.printer.utils.FileUtils;
import com.now.printer.utils.FileUtils2;
import com.now.printer.utils.PrinterUtils;
import com.xuexiang.xaop.annotation.Permission;
import com.xuexiang.xutil.display.ImageUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.util.DensityUtil;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xuexiang.xaop.consts.PermissionConsts.STORAGE;

/**
 * 预览和打印
 * Created by xudong on 2021/5/18.
 */
public class FilePreviewAndPrintActivity extends BaseActivity2 {

    public final static String INTENT_KEY_ID_CARD_FRONT_BACK = "INTENT_KEY_ID_CARD_FRONT_BACK";


    public final static String INTENT_KEY_FILE_URI = "INTENT_KEY_FILE_URI";
    public final static String INTENT_KEY_FILE_NAME = "INTENT_KEY_FILE_NAME";
    public final static String INTENT_KEY_FILE_IMAGE = "INTENT_KEY_FILE_IMAGE";
    public final static String INTENT_KEY_FILE_LAST_TIME = "INTENT_KEY_FILE_LAST_TIME";
    public final static String INTENT_KEY_FILE_SIZE = "INTENT_KEY_FILE_SIZE";

    private FileReaderView fileReaderView;
    private int fileImage;
    private String fileUri = "", fileLastTime, fileSize, fileName;
    private TextView btnPrint;

    private ImageView image, image2;

    private String[] frontAndBackImagePath = null;

    private CropImageView mCropImageView1, mCropImageView2;

    private ProgressBar progressBar_convert_pdf;

    private TextView btn_plugin_print;

    public int getLayoutId() {
        return R.layout.activity_file_webview;
    }

    public void doBusiness(Context mContext) {

        initView();
        fileUri = getIntent().getStringExtra(INTENT_KEY_FILE_URI);
        LogUtil.i("预览页面获取file url is : " + fileUri);

        fileName = getIntent().getStringExtra(INTENT_KEY_FILE_NAME);
        fileImage = getIntent().getIntExtra(INTENT_KEY_FILE_IMAGE, -1);
        fileLastTime = getIntent().getStringExtra(INTENT_KEY_FILE_LAST_TIME);
        fileSize = getIntent().getStringExtra(INTENT_KEY_FILE_SIZE);

        fileReaderView = (FileReaderView) findViewById(R.id.file_reader_view);
        image = findViewById(R.id.image);
        image2 = findViewById(R.id.image2);
        mCropImageView1 = findViewById(R.id.crop_image_view);
        mCropImageView2 = findViewById(R.id.crop_image_view2);



        progressBar_convert_pdf = findViewById(R.id.progressBar_convert_pdf);
                //获取身份证
        frontAndBackImagePath = getIntent().getStringArrayExtra(CameraActivity.INTENT_KEY_ID_CARD_FRONT_BACK);

        String action = getIntent().getAction();
        //通过第三方应用打开到这里
        openThisActivityByOtherApp(action);
        //文件uri是个图片地址
        if (FileUtils.isPicFile(fileUri)) {
            image.setVisibility(View.VISIBLE);
            fileReaderView.setVisibility(View.GONE);
            x.image().bind(image, new File(fileUri).toURI().toString(), new ImageOptions.Builder()
//                    .setSize(DensityUtil.dip2px(120), DensityUtil.dip2px(120))
                    .setRadius(DensityUtil.dip2px(5))
                    // 如果ImageView的大小不是定义为wrap_content, 不要crop.
//                    .setCrop(true) // 很多时候设置了合适的scaleType也不需要它.
                    // 加载中或错误图片的ScaleType
                    //.setPlaceholderScaleType(ImageView.ScaleType.MATRIX)
                    .setImageScaleType(ImageView.ScaleType.FIT_CENTER)
                    .setLoadingDrawableId(R.mipmap.ic_launcher)
                    .setFailureDrawableId(R.mipmap.ic_launcher)
                    .setIgnoreGif(false)
                    .build());
        } else {
            //证件照的uri
            if (frontAndBackImagePath != null) {

                image.setVisibility(View.VISIBLE);
                image2.setVisibility(View.VISIBLE);

                mCropImageView1.setVisibility(View.VISIBLE);
                mCropImageView2.setVisibility(View.VISIBLE);

                float idCardScale = (float) 240 / 151;
                int idCardWidth = DensityUtil.getScreenWidth();
                int idCardHeight = (int) (idCardWidth / idCardScale);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mCropImageView1.getLayoutParams();
                layoutParams.width = idCardWidth;
                layoutParams.height = idCardHeight;
                mCropImageView1.setLayoutParams(layoutParams);
                RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) mCropImageView2.getLayoutParams();
                layoutParams2.width = idCardWidth;
                layoutParams2.height = idCardHeight;
                mCropImageView2.setLayoutParams(layoutParams2);

                LogUtil.i("屏幕宽： " + DensityUtil.getScreenWidth() + " \t 身份证高：" + idCardHeight);
                x.image().bind(image, new File(frontAndBackImagePath[0]).toURI().toString(), new ImageOptions.Builder()
                        .setSize(111, 70)
                        .setImageScaleType(ImageView.ScaleType.FIT_CENTER)
                        .setLoadingDrawableId(R.mipmap.ic_launcher)
                        .setFailureDrawableId(R.mipmap.ic_launcher)
                        .setIgnoreGif(false)
                        .build());
                x.image().bind(image2, new File(frontAndBackImagePath[1]).toURI().toString(), new ImageOptions.Builder()
                        .setSize(111, 70)
                        .setImageScaleType(ImageView.ScaleType.FIT_CENTER)
                        .setLoadingDrawableId(R.mipmap.ic_launcher)
                        .setFailureDrawableId(R.mipmap.ic_launcher)
                        .setIgnoreGif(false)
                        .build());

                mCropImageView1.setImageBitmap(ImageUtils.getBitmap(new File(frontAndBackImagePath[0])));
                mCropImageView2.setImageBitmap(ImageUtils.getBitmap(new File(frontAndBackImagePath[1])));

                return;
            } else {
                //普通文件地址
                image2.setVisibility(View.GONE);
            }
            image.setVisibility(View.GONE);
            fileReaderView.setVisibility(View.VISIBLE);
            openFile(fileUri);
        }
    }

    private void initView() {
        btnPrint = findViewById(R.id.btn_print);
        btnPrint.setOnClickListener(onClickListener);

        btn_plugin_print = findViewById(R.id.btn_plugin_print);
        btn_plugin_print.setOnClickListener(onClickListener);
    }

    //通过第三方应用打开到这里
    private void openThisActivityByOtherApp(String action) {
        if (Intent.ACTION_VIEW.equals(action)) {
            LogUtil.d("处理编码前" + getIntent().getDataString());

            Uri uri = getIntent().getData();
            fileUri = Uri.decode(uri.getEncodedPath());
            LogUtil.d("uri is ：" + uri);
            LogUtil.d("处理编码后的地址是：" + fileUri);
            String getFPUri = FileUtils2.getFPUriToPath(this, uri);
            if (TextUtils.isEmpty(getFPUri)) {
                getFPUri = FileUtils2.getFPUriToPath(this, Uri.fromFile(new File(fileUri)));
                if (TextUtils.isEmpty(getFPUri)) {
                    getFPUri = FileUtils2.getFileFromUri(this, uri);
                    if (TextUtils.isEmpty(getFPUri)) {
                        if (fileUri.startsWith("/external")) {
                            fileUri = fileUri.replaceAll("/external", "/storage/emulated/0");
                        } else if (fileUri.startsWith("/external_files")) {
                            fileUri = fileUri.replaceAll("/external_files", "");
                        }
                    }
                }
            }
            fileUri = getFPUri;
            LogUtil.d("终极处理后：" + fileUri);
        } else if (Intent.ACTION_SEND.equals(action)) {
            Uri uri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
            fileUri = Uri.decode(uri.getEncodedPath());
            LogUtil.d("ACTION_SEND 接收URI：" + uri);
            LogUtil.d("ACTION_SEND 编码后：" + fileUri);

            String getFPUri = FileUtils2.getFPUriToPath(this, Uri.fromFile(new File(fileUri)));
            if (TextUtils.isEmpty(getFPUri)) {
                getFPUri = FileUtils2.getFPUriToPath(this, uri);

                if (TextUtils.isEmpty(getFPUri)) {
                    getFPUri = FileUtils2.getFileFromUri(this, uri);

                }
            }
            fileUri = getFPUri;
            LogUtil.d("ACTION_SEND 最终编码：" + fileUri);
            return;
        }
    }

    private String packageName = "org.mopria.printplugin";

    private View.OnClickListener onClickListener = v -> {
        switch (v.getId()) {
            case R.id.btn_plugin_print:

                if (FileUtils2.checkAppInstalled(this, packageName)) {
                    doMopriaPrint(fileUri);
                } else {
                    Intent intent_download = new Intent(this, WebViewActivity.class);
                    intent_download.putExtra(WebViewActivity.INTENT_KEY_URL, "https://app.mopria.org/zh-cn/MopriaPrintService");
                    intent_download.putExtra(WebViewActivity.INTENT_KEY_TITLE, "下载插件");
                    startActivity(intent_download);
                }
                break;
            case R.id.btn_print:
                String outputPath = fileUri + ".pdf";

                if (!TextUtils.isEmpty(fileUri)) {
                    if (fileUri.endsWith(".pdf")) {
                        PrinterUtils.doPrint(this, fileUri);
                        return;
                    }
                    if (FileUtils.isExists(outputPath)) {
                        if (!PDFCheck.check(outputPath)) {
                            File file = new File(outputPath);
                            if (file.delete()) {
                                ToastUtils.toast("请重新点击打印");
                            }
                            return;
                        }
//                        PrinterUtils.doPrint(this, outputPath);
//                        return;
                    }

                    if (fileUri.endsWith(".doc") || fileUri.endsWith(".docx") ||
                            fileUri.endsWith(".xls") || fileUri.endsWith(".xlsx") ||
                            fileUri.endsWith(".ppt") || fileUri.endsWith(".pptx")) {

                        Map<String, File> fileMap = new HashMap<>();
                        fileMap.put("file", new File(fileUri));
                        Xutils.getInstance().upLoadFile("http://www.yinyaowu.cn:8066/api/app/v1/file/upload", null, fileMap, new Xutils.XDownLoadCallBack() {
                            @Override
                            public void onResponse(File result) {
                                LogUtil.i("Xutils.getInstance().upLoadFile onResponse File: " + result.toString());
                            }

                            @Override
                            public void onLoading(long total, long current, boolean isDownloading) {
                                LogUtil.i("Xutils.getInstance().upLoadFile onLoading : " + isDownloading);
                                progressBar_convert_pdf.setVisibility(View.VISIBLE);

                            }

                            @Override
                            public void onFinished() {
                                LogUtil.i("Xutils.getInstance().upLoadFile onFinished : " );
                                progressBar_convert_pdf.setVisibility(View.GONE);

                            }

                            @Override
                            public void onResponse(String result1) {
                                LogUtil.i("Xutils.getInstance().upLoadFile onResponse String: " + result1);

                                try {
                                    JSONObject jsonObject = new JSONObject(result1);
                                    String downloadConvertedPdfUrl = jsonObject.optString("data");
                                    LogUtil.i("转换为PDF后, 文件地址为: " + downloadConvertedPdfUrl );
                                    Xutils.getInstance().downLoadFile(FilePreviewAndPrintActivity.this, downloadConvertedPdfUrl, null, new Xutils.XDownLoadCallBack() {
                                        @Override
                                        public void onResponse(File result) {
                                            LogUtil.i("Xutils.getInstance().downLoadFile onResponse File: " + result);

                                            //下载的文件存在这里

                                            Message message = new Message();
                                            message.what = 1;
                                            message.obj = result.getAbsolutePath();
                                            handler.sendMessage(message);
                                        }

                                        @Override
                                        public void onLoading(long total, long current, boolean isDownloading) {
                                            LogUtil.i("Xutils.getInstance().downLoadFile onLoading: " + isDownloading);

                                        }

                                        @Override
                                        public void onFinished() {
                                            LogUtil.i("Xutils.getInstance().downLoadFile onFinished: " );
                                            progressBar_convert_pdf.setVisibility(View.GONE);

                                        }

                                        @Override
                                        public void onResponse(String result) {
                                            LogUtil.i("Xutils.getInstance().downLoadFile onResponse String: " + result);

                                        }
                                    });
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    LogUtil.i("Xutils.getInstance().upLoadFile onResponse JSONException: " + e.getMessage());
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            progressBar_convert_pdf.setVisibility(View.GONE);
                                        }
                                    });
                                }
                            }
                        });

                    } else if (fileUri.endsWith(".jpg") || fileUri.endsWith(".jpeg") || fileUri.endsWith(".png")) {
                        String finalOutputPath1 = outputPath;
                        x.task().run(new Runnable() {
                            @Override
                            public void run() {
                                ConvertUtils.convertImageToPdf(FilePreviewAndPrintActivity.this, fileUri, finalOutputPath1);
                                Message message = new Message();
                                message.what = 1;
                                message.obj = finalOutputPath1;
                                handler.sendMessage(message);
                            }
                        });

                    } else if (fileUri.endsWith(".txt")) {

                        String finalOutputPath4 = outputPath;
                        x.task().run(new Runnable() {
                            @Override
                            public void run() {
                                ConvertUtils.convertTextToPdf(fileUri, finalOutputPath4);

                                Message message = new Message();
                                message.what = 1;
                                message.obj = finalOutputPath4;
                                handler.sendMessage(message);
                            }
                        });
                    }
                } else {
                    setCropFrontAndBack();
                    outputPath = FileUtils.getCurrentAppPath(this) + File.separator + "证件照.pdf";
                    //为证件照设计
                    if (frontAndBackImagePath != null && TextUtils.isEmpty(fileUri)) {
                        String finalOutputPath2 = outputPath;
                        x.task().run(new Runnable() {
                            @Override
                            public void run() {
                                ConvertUtils.convertImageToPdf(FilePreviewAndPrintActivity.this, frontAndBackImagePath, finalOutputPath2);
                                Message message = new Message();
                                message.what = 1;
                                message.obj = finalOutputPath2;
                                handler.sendMessage(message);
                            }
                        });
                    }
                }
//                PrinterUtils.doPrint(this, outputPath);
                saveCurrentFileToDatabase(fileUri);
                break;
        }
    };

    private boolean cropFront = false;
    private boolean cropBack = false;

    private void setCropFrontAndBack() {
        /*手动裁剪图片*/
        mCropImageView1.crop(new CropListener() {
            @Override
            public void onFinish(Bitmap bitmap) {
                if (bitmap == null) {
                    Toast.makeText(getApplicationContext(), getString(R.string.crop_fail), Toast.LENGTH_SHORT).show();
                    finish();
                    cropFront = false;
                }
                /*保存图片到sdcard并返回图片路径*/
                String imagePath = FileUtils.getCurrentAppPath(FilePreviewAndPrintActivity.this)
                        + File.separator
                        + System.currentTimeMillis() + ".jpg";
                if (ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.JPEG)) {
                    cropFront = true;
                    frontAndBackImagePath[0] = imagePath;
                }
            }
        }, true);
        /*手动裁剪图片*/
        mCropImageView2.crop(new CropListener() {
            @Override
            public void onFinish(Bitmap bitmap) {
                if (bitmap == null) {
                    Toast.makeText(getApplicationContext(), getString(R.string.crop_fail), Toast.LENGTH_SHORT).show();
                    finish();
                    cropBack = false;
                }
                /*保存图片到sdcard并返回图片路径*/
                String imagePath = FileUtils.getCurrentAppPath(FilePreviewAndPrintActivity.this)
                        + File.separator
                        + System.currentTimeMillis() + ".jpg";
                if (com.now.printer.idcardcamera.utils.ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.JPEG)) {
                    cropBack = true;
                    frontAndBackImagePath[1] = imagePath;
                }
            }
        }, true);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                PrinterUtils.doPrint(FilePreviewAndPrintActivity.this, (String) msg.obj);
            }
        }
    };

    /**
     * 打开文件
     *
     * @param fileUri
     */
    @Permission(STORAGE)
    private void openFile(String fileUri) {
        if (!TextUtils.isEmpty(fileUri)) {
            fileReaderView.show(fileUri);
        } else {
            ToastUtils.toast("文件路径无效！");
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        if (fileReaderView != null) {
            fileReaderView.stop();
        }
        super.onDestroy();
    }


    //打印完毕后保存当前文档
    private void saveCurrentFileToDatabase(String filePath) {
        x.task().run(new Runnable() {
            @Override
            public void run() {
                try {
                    DbManager db = x.getDb(DbUtils.daoConfig);

                    List<RecentlyTable> recentlyTableList = db.selector(RecentlyTable.class).findAll();

                    RecentlyTable recentlyTable = new RecentlyTable();
                    recentlyTable.setPath(filePath);
                    recentlyTable.setName(fileName);
                    recentlyTable.setImageId(fileImage);

                    if (recentlyTableList == null) {
                        recentlyTable.setIsCollected("false");
                    }

                    recentlyTable.setSize(fileSize);
                    recentlyTable.setLastTime(fileLastTime);
                    db.saveOrUpdate(recentlyTable);

                } catch (DbException e) {
                    e.printStackTrace();
                    LogUtil.i("saveCurrentFileToDatabase DbException：" + e.getMessage());

                }
            }
        });

    }


    private void doMopriaPrint(String filePath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);

//        String className = "org.mopria.printplugin.DocumentRenderingActivity";  //这个貌似作废
        String className = "org.mopria.printplugin.ShareToPrintWithoutOfficeActivity";
        intent.setClassName(packageName, className);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String mimeType = FileUtils.getMIMEType(new File(filePath));
        LogUtil.i("文件类型是: " + mimeType);
        intent.setType(mimeType);
        //
        Uri data = null;
        //
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判断android版本大于等于7.0
            //由于 从Android 7.0开始，不再允许在app中把file:// Uri暴露给其他app，否则应用会抛出FileUriExposedException
            //使用FileProvider生成"content://" Uri来替代"file://" Uri，解决该异常
            String authority = getApplicationContext().getPackageName() + ".fileprovider";
            data = FileProvider.getUriForFile(this, authority, new File(filePath));
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(new File(filePath));
        }
        intent.setData(data);

        startActivity(intent);
    }


}
